<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/6 12:02
 */

namespace module\ai\logic;

use module\ai\library\channel\Factory;
use module\ai\library\channel\interface\ConfigInterface;
use module\ai\model\Channel;
use mof\Logic;
use mof\Model;
use think\exception\ValidateException;

class ChannelLogic extends Logic
{
    /**
     * @var Channel
     */
    protected $model;

    public function save($params): Model
    {
        //验证配置参数
        $instance = Factory::config($params['flag']);
        $instance->validateConfig($params['config']);

        return parent::save($params);
    }

    public function update($id, $params): Model
    {
        //更新数据里去掉主键信息
        if (isset($params[$this->model->getPk()])) {
            unset($params[$this->model->getPk()]);
        }

        $model = $this->read($id);
        if ($params['flag'] !== $model->flag) {
            throw new ValidateException('不能修改通道类型');
        }

        //验证配置参数
        $instance = Factory::config($params['flag']);
        $instance->validateConfig($params['config']);

        $model->save($params);
        return $model;
    }

    public function getModelByFlag($flag): Channel
    {
        $model = $this->model->where('flag', $flag)->find();
        if (!$model) {
            $instance = Factory::config($flag);
            $model = $this->model->newInstance([
                'flag' => $flag,
                'name' => $instance->getName()
            ]);
        }
        return $model;
    }

    /**
     * 获取列表
     * @return array
     */
    public function getFlagList(): array
    {
        $dict = Factory::platformDict();
        $result = [];
        $classes = Factory::configClass();
        foreach ($classes as $class) {
            /** @var ConfigInterface $instance */
            $instance = new $class();
            $result[] = [
                'flag' => $instance->getFlag(),
                'name' => $dict->findValue($instance->getFlag())
            ];
        }
        return $result;
    }

}